import "./App.css";
import React, { useEffect, useState, Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router";
import { UserContext } from "./store/user";
import RouteView from './route/index'
// https://karlhadwen.medium.com/code-splitting-react-router-routes-with-react-lazy-and-react-suspense-a3852b42c0a9

function App() {
  const [userInfo, setUserInfo] = useState(null);
  const login = (u) => {
    if( !u ){
      logout();
      return;
    }
    localStorage['userInfo'] = JSON.stringify(u);
    setUserInfo(u)
  };
  const logout = () => {
    setUserInfo(null)
    delete localStorage['userInfo']
  };

  useEffect(() => {
    // console.log('aaa')
    // setUserInfo({
    //   name: "blue",
    //   age: 18,
    // });
    if( localStorage['userInfo'] ){
      login(JSON.parse(localStorage['userInfo']))
    }
  }, []);

  return (
    <UserContext.Provider value={{ user: userInfo, login, logout }}>
      <BrowserRouter>
        <Suspense fallback={<div className="home-loading" >加载中…</div>}>
          <RouteView />
        </Suspense>
      </BrowserRouter>
    </UserContext.Provider>
  );
}

export default App;
